package com.ascent.client.ui;

import javax.swing.*;
import javax.swing.event.*;

import com.ascent.bean.Product;
import com.ascent.bean.User;
import com.ascent.client.util.ProductDataClient;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import java.io.*;

/**
 * 这个类构建产品面板
 * @author ascent
 * @version 1.0
 */
@SuppressWarnings("serial")
public class ProductPanel extends JPanel {

    protected JLabel selectionLabel;

    protected JComboBox<String> categoryComboBox;

    protected JPanel topPanel;

    protected JList<Object> productListBox;

    protected JScrollPane productScrollPane;

    protected JButton detailsButton;

    protected JButton addButton;
    protected JButton updateButton;

    protected JButton deleteButton;

    protected JButton exitButton;

    protected JButton shoppingButton;

    protected JPanel bottomPanel;

    protected MainFrame parentFrame;

    protected ArrayList<Product> productArrayList;

    protected ProductDataClient myDataClient;

    /**
     * 构建产品面板的构造方法
     * @param theParentFrame 面板的父窗体
     */
    public ProductPanel(MainFrame theParentFrame) {
        try {
            parentFrame = theParentFrame;
            myDataClient = new ProductDataClient();
            selectionLabel = new JLabel("选择类别");
            categoryComboBox = new JComboBox<>();
            updateCategory();

            topPanel = new JPanel();
            productListBox = new JList<>();
            productListBox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            productScrollPane = new JScrollPane(productListBox);

            addButton = new JButton("新增药品");
            updateButton = new JButton("修改");
            deleteButton = new JButton("删除药品");
            detailsButton = new JButton("详细...");
            exitButton = new JButton("退出");
            shoppingButton = new JButton("查看购物车");

            bottomPanel = new JPanel();

            this.setLayout(new BorderLayout());

            topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            topPanel.add(selectionLabel);
            topPanel.add(categoryComboBox);

            this.add(BorderLayout.NORTH, topPanel);
            this.add(BorderLayout.CENTER, productScrollPane);

            bottomPanel.setLayout(new FlowLayout());
            //权限区分
            if (theParentFrame.localUser.getAuthority() == 1){

                bottomPanel.add(addButton);
                bottomPanel.add(updateButton);
                bottomPanel.add(detailsButton);
                bottomPanel.add(deleteButton);
                addButton.addActionListener(new AddActionListener());
                updateButton.addActionListener(new UpdateActionListener());
                detailsButton.addActionListener(new DetailsActionListener());
                deleteButton.addActionListener(new DeleteActionListener());
                detailsButton.setEnabled(false);
                updateButton.setEnabled(false);
                deleteButton.setEnabled(false);
            }else{
                bottomPanel.add(shoppingButton);
                bottomPanel.add(detailsButton);
                bottomPanel.add(exitButton);
                detailsButton.addActionListener(new DetailsActionListener());
                exitButton.addActionListener(new ExitActionListener());
                shoppingButton.addActionListener(new ShoppingActionListener());
                detailsButton.setEnabled(false);
                shoppingButton.setEnabled(false);
            }
            this.add(BorderLayout.SOUTH, bottomPanel);
            categoryComboBox.addItemListener(new GoItemListener());
            productListBox.addListSelectionListener(new ProductListSelectionListener());

        } catch (IOException exc) {
            JOptionPane.showMessageDialog(this, "网络问题 " + exc, "网络问题", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
    }

    /**
     * 从服务器更新分类列表
     * @throws IOException
     */
    private void updateCategory() throws IOException {
        categoryComboBox.removeAllItems();
        categoryComboBox.addItem("-------");
        ArrayList<String> categoryArrayList = myDataClient.getCategories();

        Iterator<String> iterator = categoryArrayList.iterator();
        String aCategory;
        while (iterator.hasNext()) {
            aCategory = (String) iterator.next();
            categoryComboBox.addItem(aCategory);
        }
    }
    /**
     * 从服务器更新列表数据
     */
    private void updateList() throws IOException {
        String category = (String) categoryComboBox.getSelectedItem();
        assert category != null;
        if (!category.startsWith("---")) {
            productArrayList = myDataClient.getProducts(category);
        } else {
            productArrayList = new ArrayList<Product>();
        }
        Object[] theData = productArrayList.toArray();

        System.out.println(productArrayList + ">>>>>>>>>>>");
        productListBox.setListData(theData);
        productListBox.updateUI();
    }
    /**
     * 设置下拉列选中的分类选项
     */
    protected void populateListBox() {
        try {
            updateList();
        } catch (IOException exc) {
            JOptionPane.showMessageDialog(this, "网络问题: " + exc, "网络问题", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
    }

    /**
     * 处理选择详细...按钮时触发的事件监听器
     * @author ascent
     */
    class DetailsActionListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            int index = productListBox.getSelectedIndex();
            Product product = (Product) productArrayList.get(index);
            ProductDetailsDialog myDetailsDialog = new ProductDetailsDialog(parentFrame, product, shoppingButton);
            myDetailsDialog.setVisible(true);
        }
    }

    /**
     * 处理选择删除按钮时触发的事件监听器
     * @author ascent
     */
    class DeleteActionListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            try{
                ConfirmFrame confirmFrame = new ConfirmFrame("删除用户");
                confirmFrame.addWindowListener(new WindowAdapter() {
                    @Override
                    public void windowClosed(WindowEvent e) {
                        if (confirmFrame.isTrue()){
                            int index = productListBox.getSelectedIndex();
                            Product product = (Product) productArrayList.get(index);
                            myDataClient.deleteProduct(product);

                            //更新药品列表
                            productArrayList.remove(index);
                            if (productArrayList.size() == 0){
                                categoryComboBox.setSelectedItem("-------");
                                try {
                                    updateCategory();
                                } catch (IOException ex) {
                                    throw new RuntimeException(ex);
                                }
                                try {
                                    updateList();
                                } catch (IOException ex) {
                                    throw new RuntimeException(ex);
                                }
                                return;
                            }
                            Object[] theData = productArrayList.toArray();
                            productListBox.setListData(theData);
                            productListBox.updateUI();
                        }
                    }
                });
                confirmFrame.setVisible(true);
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

    /**
     * 处理选择查看购物车按钮时触发的事件监听器
     * @author ascent
     */
    class ShoppingActionListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            ShoppingCartDialog myShoppingDialog = new ShoppingCartDialog(
                    parentFrame, shoppingButton);
            myShoppingDialog.setVisible(true);
        }
    }



    /**
     * 处理新增药品按钮时触发的事件触发器
     */
    class AddActionListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            AddProductFrame addProductFrame = new AddProductFrame();
            addProductFrame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                    try {
                        String categoryText = addProductFrame.getCategoryText();
                        System.out.println("修改后的分类"+categoryText);
                        if (categoryText == null){
                            return;
                        }
                        updateCategory();
                        categoryComboBox.setSelectedItem(categoryText);
                        updateList();
                    } catch (IOException exc) {
                        System.exit(1);
                    }
                }
            });
            addProductFrame.setVisible(true);
        }
    }

    /**
     * 处理修改按钮时触发的事件触发器
     */
    class UpdateActionListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            int index = productListBox.getSelectedIndex();
            Product product = (Product) productArrayList.get(index);
            UpdateProductFrame updateProductFrame = new UpdateProductFrame(product);

            updateProductFrame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                    try {
                        updateCategory();
                        String categoryText = updateProductFrame.getCategoryText();
                        System.out.println("修改后的分类"+categoryText);
                        categoryComboBox.setSelectedItem(categoryText);
                        updateList();
                    } catch (IOException exc) {
                        System.exit(1);
                    }
                }
            });
            updateProductFrame.setVisible(true);
        }
    }


    /**
     * 处理选择退出按钮时触发的事件监听器
     * @author ascent
     */
    class ExitActionListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            parentFrame.exit();
        }
    }



    /**
     * 处理选中分类下拉列选的选项时触发的事件监听器
     * @author ascent
     */
    class GoItemListener implements ItemListener {
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                populateListBox();
            }
        }
    }

    /**
     * 处理选中分类列表中选项时触发的事件监听器
     * @author ascent
     */
    class ProductListSelectionListener implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent event) {
            if (productListBox.isSelectionEmpty()) {
                if (detailsButton != null){
                    detailsButton.setEnabled(false);
                }
                if (updateButton!=null){
                    updateButton.setEnabled(false);
                }
                if (deleteButton != null) {
                    deleteButton.setEnabled(false);
                }

            } else {
                if (detailsButton != null){
                    detailsButton.setEnabled(true);
                }
                if (updateButton!=null){
                    updateButton.setEnabled(true);
                }
                if (deleteButton != null){
                    deleteButton.setEnabled(true);
                }
            }
        }
    }

}